#!/bin/bash
#^#
#
# Copyright (C) 2006, 2007 Oracle.  All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 021110-1307, USA.
#$#


attr_array=(ip_port ip_address number name cluster)
idx_of() {
    for ((i=0;i<${#attr_array};i++)) {
        if [ x$1 == x${attr_array[$i]} ]; then
            echo $i; return
        fi
    }
    echo "-1"
}

idx=-1
while read line; do
    if (echo $line | grep -qE "(^\s*$)|(^#.*)"); then #empty line or comment
        continue
    elif (echo $line | grep -q "^\s*cluster:"); then #node:
        break
    elif (echo $line | grep -q "^\s*node:"); then #node:
        idx=$((idx+1))
    else
	set -- $(echo $line | sed -e "s/=/ /")
	#echo "node$idx[$(idx_of $1)]=$2"
        eval "node$idx[$(idx_of $1)]=$2"
    fi
done < /etc/ocfs2/cluster.conf

cluster_name=${node0[4]}
if [ ! -n "$cluster_name" ]; then
    #empty cluster, do nothing
    exit 0
fi


if (service o2cb status 2>/dev/null | grep -q -E "Checking O2CB cluster \w+: Online"); then
    mv /etc/ocfs2/cluster.conf /etc/ocfs2/cluster.conf.orig
    cat >/etc/ocfs2/cluster.conf <<EOF
cluster:
        node_count = 0
        name = $cluster_name
EOF


    #add all the nodes to the cluster
    for((i=0;i<=$idx;i++)); do
        eval name=\${node$i[3]}
        ab_name=${name/%.*/}
        if [ -d /sys/kernel/config/cluster/$cluster_name/node/$ab_name ] \
                || ( ls /sys/kernel/config/cluster/ocfs2/node/$ab_name.* &>/dev/null ); then
            continue
        fi
        #o2cb_ctl -C -i -n NODENAME -t node -a number=NODENUM -a ip_address=IPADDR -a ip_port=IPPORT -a cluster=CLUSTERNAME
        eval o2cb_ctl -C -i -n \${node$i[3]} -t node \
                -a number=\${node$i[2]} \
                -a ip_address=\${node$i[1]} \
                -a ip_port=\${node$i[0]} \
                -a cluster=\${node$i[4]}
    done

    mv /etc/ocfs2/cluster.conf.orig /etc/ocfs2/cluster.conf
fi

#reconfigure the cluster
service o2cb configure &>/dev/null <<EOF
y
o2cb
$cluster_name




EOF

#ocfs2 1.4 compatibility
if [ ! $? == 0 ]; then
service o2cb configure &>/dev/null <<EOF
y
$cluster_name




EOF
fi

#always return success, and check the status afterward
exit 0
